﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SuperListEx.ItemLists
{
  public class BetterItemList : ItemList
  {
    public List<object> _internalList;
    public BetterItemList()
    {
      _internalList = new List<object>();
    }

    public override int Count
    {
      get { return _internalList.Count; }
    }

    public override object this[int index]
    {
      get { return _internalList[index]; }
    }

    public override void Add(object item)
    {
      _internalList.Add(item);
      Sort();
      ListControl.UpdateListSection(false);
    }

    public override void AddRange(System.Collections.IEnumerable items)
    {
      foreach (object o in items)
        _internalList.Add(o);
      Sort();
      ListControl.UpdateListSection(false);
    }

    public override void Remove(object item)
    {
      _internalList.Remove(item);
      ListControl.UpdateListSection(false);
    }

    public override void RemoveRange(System.Collections.IEnumerable items)
    {
      foreach (object o in items)
        _internalList.Remove(o);

      ListControl.UpdateListSection(false);
    }

    public override void Clear()
    {
      _internalList.Clear();
      ListControl.UpdateListSection(false);
    }

    public override List<object> ToList()
    {
      return _internalList;
    }

    public override void ItemsChanged(params object[] items)
    {
      ListControl.UpdateListSection(true);
    }

    public override int IndexOf(object o)
    {
      return _internalList.IndexOf(o);
    }

    public override void Sort()
    {
      ColumnComparer comparer = new ColumnComparer(GetGroupColumnsCopy().ToArray(), GetSortColumnsCopy().ToArray(), this);
      _internalList.Sort(comparer.Compare);
      ListControl.UpdateListSection(true);
    }

    private List<Column> GetSortColumnsCopy()
    {
      List<Column> columns = new List<Column>();

      foreach (Column column in ListControl.Columns.VisibleItems)
      {
        if (column.SortOrder != System.Windows.Forms.SortOrder.None)
        {
          columns.Add(new Column(column));
        }
      }
      return columns;
    }

    private List<Column> GetGroupColumnsCopy()
    {
      List<Column> columns = new List<Column>();

      foreach (Column column in ListControl.Columns.GroupedItems)
      {
        columns.Add(new Column(column));
      }
      return columns;
    }

    public override bool Contains(object o)
    {
      return _internalList.Contains(o);
    }
  }
}
